1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
| import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.lettuce.core.api.async.RedisAsyncCommands; import io.lettuce.core.cluster.api.async.RedisClusterAsyncCommands; import io.lettuce.core.codec.ByteArrayCodec; import io.lettuce.core.output.*; import io.lettuce.core.protocol.CommandArgs; import io.lettuce.core.protocol.ProtocolKeyword; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.connection.ClusterSlotHashUtil; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.lettuce.LettuceClusterConnection; import org.springframework.data.redis.connection.lettuce.LettuceConnection; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.lang.NonNull; import org.springframework.lang.Nullable; import org.springframework.stereotype.Component; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.TimeUnit;
@Slf4j @Component public class RedisJsonTemplate {
private final StringRedisTemplate redisTemplate; private final ObjectMapper objectMapper;
public RedisJsonTemplate(StringRedisTemplate redisTemplate, ObjectMapper objectMapper) { this.redisTemplate = redisTemplate; this.objectMapper = objectMapper; }
private static final byte[] PATH_ROOT_BYTES = "$".getBytes(StandardCharsets.UTF_8); private static final byte[] CONDITION_NX_BYTES = "NX".getBytes(StandardCharsets.UTF_8); private static final byte[] CONDITION_XX_BYTES = "XX".getBytes(StandardCharsets.UTF_8);
private enum RedisJsonCommand implements ProtocolKeyword { JSON_SET("JSON.SET"), JSON_GET("JSON.GET"), JSON_MGET("JSON.MGET"), JSON_DEL("JSON.DEL"), JSON_TYPE("JSON.TYPE"), JSON_ARRAPPEND("JSON.ARRAPPEND"), JSON_ARRLEN("JSON.ARRLEN"), JSON_NUMINCRBY("JSON.NUMINCRBY"), JSON_STRLEN("JSON.STRLEN"), JSON_OBJLEN("JSON.OBJLEN");
@Getter private final String command; private final byte[] name;
RedisJsonCommand(String name) { this.name = name.getBytes(StandardCharsets.UTF_8); this.command = name; }
@Override public byte[] getBytes() { return name; } }
public <T> Boolean jsonSet(@NonNull String key, @NonNull T value) { return jsonSet(key, "$", value); }
public <T> Boolean jsonSet(@NonNull String key, @NonNull String path, @NonNull T value) { try { byte[] jsonBytes = objectMapper.writeValueAsBytes(value); byte[] pathBytes = "$".equals(path) ? PATH_ROOT_BYTES : path.getBytes(StandardCharsets.UTF_8); return executeStatusCommand(RedisJsonCommand.JSON_SET, key.getBytes(StandardCharsets.UTF_8), pathBytes, jsonBytes); } catch (JsonProcessingException e) { throw new IllegalArgumentException("对象序列化 JSON 失败 key=" + key, e); } }
public <T> Boolean jsonSetNX(@NonNull String key, @NonNull T value) { return jsonSetWithCondition(key, "$", value, CONDITION_NX_BYTES); }
public <T> Boolean jsonSetXX(@NonNull String key, @NonNull T value) { return jsonSetWithCondition(key, "$", value, CONDITION_XX_BYTES); }
private <T> Boolean jsonSetWithCondition(String key, String path, T value, byte[] conditionBytes) { try { byte[] jsonBytes = objectMapper.writeValueAsBytes(value); byte[] pathBytes = "$".equals(path) ? PATH_ROOT_BYTES : path.getBytes(StandardCharsets.UTF_8); return executeStatusCommand(RedisJsonCommand.JSON_SET, key.getBytes(StandardCharsets.UTF_8), pathBytes, jsonBytes, conditionBytes); } catch (JsonProcessingException e) { throw new IllegalArgumentException("对象序列化 JSON 失败 key=" + key, e); } }
@Nullable public <T> T jsonGet(@NonNull String key, @NonNull Class<T> clazz) { return jsonGet(key, "$", clazz); }
@Nullable public <T> T jsonGet(@NonNull String key, @NonNull String path, @NonNull Class<T> clazz) { byte[] pathBytes = "$".equals(path) ? PATH_ROOT_BYTES : path.getBytes(StandardCharsets.UTF_8); byte[] rawResult = executeByteArrayCommand(RedisJsonCommand.JSON_GET, key.getBytes(StandardCharsets.UTF_8), pathBytes);
if (rawResult == null || rawResult.length == 0 || isNullLiteral(rawResult)) { return null; }
try { if (path.startsWith("$")) { JsonNode rootNode = objectMapper.readTree(rawResult); if (rootNode.isArray()) { if (rootNode.isEmpty()) return null; JsonNode first = rootNode.get(0); if (first.isNull()) return null; return objectMapper.treeToValue(first, clazz); } } return objectMapper.readValue(rawResult, clazz); } catch (Exception e) { log.error("RedisJSON 反序列化失败 key={}, path={}", key, path, e); throw new RuntimeException("RedisJSON 反序列化失败", e); } }
@Nullable public String jsonGetMultiPath(@NonNull String key, @NonNull String... paths) { int pathsLen = (paths != null && paths.length > 0) ? paths.length : 1; byte[][] args = new byte[1 + pathsLen][]; args[0] = key.getBytes(StandardCharsets.UTF_8);
if (paths != null && paths.length > 0) { for (int i = 0; i < paths.length; i++) { args[i + 1] = paths[i].getBytes(StandardCharsets.UTF_8); } } else { args[1] = PATH_ROOT_BYTES; }
byte[] jsonBytes = executeByteArrayCommand(RedisJsonCommand.JSON_GET, args); return jsonBytes != null ? new String(jsonBytes, StandardCharsets.UTF_8) : null; }
@NonNull public <T> List<T> jsonMGet(@NonNull List<String> keys, @NonNull Class<T> clazz) { return jsonMGet(keys, "$", clazz); }
@NonNull public <T> List<T> jsonMGet(@NonNull List<String> keys, @NonNull String path, @NonNull Class<T> clazz) { if (keys == null || keys.isEmpty()) { return Collections.emptyList(); }
if (isClusterMode()) { int slot = -1; for (String key : keys) { int s = calculateSlot(key); if (slot == -1) slot = s; if (slot != s) { throw new IllegalArgumentException("JSON.MGET 在 Redis Cluster 下要求所有 key 必须在同一个 slot,请使用 hash tag。key=" + key); } } }
byte[] pathBytes = "$".equals(path) ? PATH_ROOT_BYTES : path.getBytes(StandardCharsets.UTF_8); byte[][] args = new byte[keys.size() + 1][]; for (int i = 0; i < keys.size(); i++) { args[i] = keys.get(i).getBytes(StandardCharsets.UTF_8); } args[keys.size()] = pathBytes;
List<byte[]> rawResults = executeArrayCommand(RedisJsonCommand.JSON_MGET, args);
if (rawResults == null || rawResults.isEmpty()) { return Collections.emptyList(); }
List<T> resultList = new ArrayList<>(rawResults.size()); for (byte[] bytes : rawResults) { if (bytes == null || bytes.length == 0 || isNullLiteral(bytes)) { resultList.add(null); continue; } try { if (path.startsWith("$")) { JsonNode rootNode = objectMapper.readTree(bytes); if (rootNode.isArray() && !rootNode.isEmpty()) { resultList.add(objectMapper.treeToValue(rootNode.get(0), clazz)); continue; } } resultList.add(objectMapper.readValue(bytes, clazz)); } catch (Exception e) { log.error("jsonMGet 局部元素反序列化失败", e); resultList.add(null); } } return resultList; }
public Long jsonDel(@NonNull String key) { return jsonDel(key, "$"); }
public Long jsonDel(@NonNull String key, @NonNull String path) { byte[] pathBytes = "$".equals(path) ? PATH_ROOT_BYTES : path.getBytes(StandardCharsets.UTF_8); return executeLongCommand(RedisJsonCommand.JSON_DEL, key.getBytes(StandardCharsets.UTF_8), pathBytes); }
@Nullable public String jsonType(@NonNull String key, @NonNull String path) { byte[] pathBytes = "$".equals(path) ? PATH_ROOT_BYTES : path.getBytes(StandardCharsets.UTF_8); byte[] rawResult = executeByteArrayCommand(RedisJsonCommand.JSON_TYPE, key.getBytes(StandardCharsets.UTF_8), pathBytes); return rawResult != null ? new String(rawResult, StandardCharsets.UTF_8) : null; }
@SafeVarargs public final <T> Long jsonArrAppend(@NonNull String key, @NonNull String path, @NonNull T... values) { if (values == null || values.length == 0) { return 0L; }
try { byte[] pathBytes = "$".equals(path) ? PATH_ROOT_BYTES : path.getBytes(StandardCharsets.UTF_8); byte[][] args = new byte[2 + values.length][]; args[0] = key.getBytes(StandardCharsets.UTF_8); args[1] = pathBytes;
for (int i = 0; i < values.length; i++) { args[2 + i] = objectMapper.writeValueAsBytes(values[i]); }
return executeLongCommand(RedisJsonCommand.JSON_ARRAPPEND, args); } catch (JsonProcessingException e) { throw new IllegalArgumentException("数组元素 JSON 序列化失败", e); } }
public Long jsonArrLen(@NonNull String key, @NonNull String path) { byte[] pathBytes = "$".equals(path) ? PATH_ROOT_BYTES : path.getBytes(StandardCharsets.UTF_8); return executeLongCommand(RedisJsonCommand.JSON_ARRLEN, key.getBytes(StandardCharsets.UTF_8), pathBytes); }
public Double jsonNumIncrBy(@NonNull String key, @NonNull String path, double increment) { byte[] pathBytes = "$".equals(path) ? PATH_ROOT_BYTES : path.getBytes(StandardCharsets.UTF_8); byte[] incBytes = String.valueOf(increment).getBytes(StandardCharsets.UTF_8); return executeDoubleCommand(RedisJsonCommand.JSON_NUMINCRBY, key.getBytes(StandardCharsets.UTF_8), pathBytes, incBytes); }
public Long jsonStrLen(@NonNull String key, @NonNull String path) { byte[] pathBytes = "$".equals(path) ? PATH_ROOT_BYTES : path.getBytes(StandardCharsets.UTF_8); return executeLongCommand(RedisJsonCommand.JSON_STRLEN, key.getBytes(StandardCharsets.UTF_8), pathBytes); }
public Long jsonObjLen(@NonNull String key, @NonNull String path) { byte[] pathBytes = "$".equals(path) ? PATH_ROOT_BYTES : path.getBytes(StandardCharsets.UTF_8); return executeLongCommand(RedisJsonCommand.JSON_OBJLEN, key.getBytes(StandardCharsets.UTF_8), pathBytes); }
@SuppressWarnings("unchecked") private Object getLettuceAsyncCommands(RedisConnection connection) { Object nativeConn = connection.getNativeConnection();
if (nativeConn instanceof RedisClusterAsyncCommands<?, ?> clusterCmds) { return clusterCmds; }
if (nativeConn instanceof RedisAsyncCommands<?, ?> asyncCmds) { return asyncCmds; }
if (connection instanceof LettuceConnection lc) { return lc.getNativeConnection(); } if (connection instanceof LettuceClusterConnection lcc) { return lcc.getNativeConnection(); }
if (nativeConn != null) { return nativeConn; }
throw new IllegalStateException("无法获取 Lettuce AsyncCommands"); }
@SuppressWarnings("unchecked") private <T> T dispatchCustomCommand(RedisConnection connection, RedisJsonCommand cmd, CommandOutput<byte[], byte[], T> output, byte[]... args) { Object asyncCmds = getLettuceAsyncCommands(connection); CommandArgs<byte[], byte[]> cmdArgs = buildArgs(args); CustomCommandType commandType = new CustomCommandType(cmd.getCommand());
if (asyncCmds instanceof RedisClusterAsyncCommands) { RedisClusterAsyncCommands<byte[], byte[]> clusterCmds = (RedisClusterAsyncCommands<byte[], byte[]>) asyncCmds; return clusterCmds.dispatch(commandType, output, cmdArgs) .toCompletableFuture() .join(); }
if (asyncCmds instanceof RedisAsyncCommands) { RedisAsyncCommands<byte[], byte[]> singleCmds = (RedisAsyncCommands<byte[], byte[]>) asyncCmds; return singleCmds.dispatch(commandType, output, cmdArgs) .toCompletableFuture() .join(); } throw new IllegalStateException("不支持的 Lettuce AsyncCommands 类型: " + asyncCmds.getClass().getName()); }
private Long executeLongCommand(RedisJsonCommand cmd, byte[]... args) { return redisTemplate.execute((RedisCallback<Long>) connection -> dispatchCustomCommand(connection, cmd, new IntegerOutput<>(ByteArrayCodec.INSTANCE), args) ); }
private Double executeDoubleCommand(RedisJsonCommand cmd, byte[]... args) { return redisTemplate.execute((RedisCallback<Double>) connection -> dispatchCustomCommand(connection, cmd, new DoubleOutput<>(ByteArrayCodec.INSTANCE), args) ); }
private Boolean executeStatusCommand(RedisJsonCommand cmd, byte[]... args) { return redisTemplate.execute((RedisCallback<Boolean>) connection -> { String status = dispatchCustomCommand(connection, cmd, new StatusOutput<>(ByteArrayCodec.INSTANCE), args); return "OK".equalsIgnoreCase(status); }); }
private byte[] executeByteArrayCommand(RedisJsonCommand cmd, byte[]... args) { return redisTemplate.execute((RedisCallback<byte[]>) connection -> dispatchCustomCommand(connection, cmd, new ByteArrayOutput<>(ByteArrayCodec.INSTANCE), args) ); }
@SuppressWarnings("unchecked") private List<byte[]> executeArrayCommand(RedisJsonCommand cmd, byte[]... args) { return redisTemplate.execute((RedisCallback<List<byte[]>>) connection -> { List<Object> rawList = dispatchCustomCommand(connection, cmd, new ArrayOutput<>(ByteArrayCodec.INSTANCE), args); if (rawList == null || rawList.isEmpty()) { return Collections.emptyList(); } List<byte[]> result = new ArrayList<>(rawList.size()); for (Object item : rawList) { result.add((byte[]) item); } return result; }); }
private record CustomCommandType(String name) implements io.lettuce.core.protocol.ProtocolKeyword { @Override public byte[] getBytes() { return name.getBytes(java.nio.charset.StandardCharsets.UTF_8); }
@Override public String name() { return name; } }
private CommandArgs<byte[], byte[]> buildArgs(byte[]... args) { CommandArgs<byte[], byte[]> cmdArgs = new CommandArgs<>(ByteArrayCodec.INSTANCE); if (args != null) { for (byte[] arg : args) { cmdArgs.add(arg); } } return cmdArgs; }
private boolean isNullLiteral(byte[] bytes) { if (bytes == null) return true; if (bytes.length == 0) return true; if (bytes.length == 4 && bytes[0] == 'n' && bytes[1] == 'u' && bytes[2] == 'l' && bytes[3] == 'l') return true; if (bytes.length == 6 && bytes[0] == '"' && bytes[1] == 'n' && bytes[2] == 'u' && bytes[3] == 'l' && bytes[4] == 'l' && bytes[5] == '"') return true; return false; }
private boolean isClusterMode() { RedisConnectionFactory factory = redisTemplate.getConnectionFactory(); if (factory instanceof LettuceConnectionFactory lcf) { return lcf.getClusterConfiguration() != null; } return false; }
private static int calculateSlot(String key) { int start = key.indexOf('{'); int end = key.indexOf('}', start + 1); if (start >= 0 && end > start) { return ClusterSlotHashUtil.calculateSlot(key.substring(start + 1, end)); } return ClusterSlotHashUtil.calculateSlot(key); }
private Double toDouble(byte[] bytes) { if (bytes == null || bytes.length == 0 || isNullLiteral(bytes)) { return null; } if (bytes[0] == '[') { try { JsonNode node = objectMapper.readTree(bytes); if (node.isArray() && !node.isEmpty()) { return node.get(0).asDouble(); } } catch (Exception ignored) { } } try { return Double.parseDouble(new String(bytes, StandardCharsets.UTF_8)); } catch (NumberFormatException e) { return null; } }
public Boolean exists(@NonNull String key) { return redisTemplate.hasKey(key); }
public Boolean delete(@NonNull String key) { return redisTemplate.delete(key); }
public Long delete(@NonNull Collection<String> keys) { return redisTemplate.delete(keys); }
public Boolean expire(@NonNull String key, long timeout, TimeUnit unit) { return redisTemplate.expire(key, timeout, unit); }
public Boolean expireAt(@NonNull String key, Date date) { return redisTemplate.expireAt(key, date); } }
|